package top.ckxgzxa.newscms.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import top.ckxgzxa.newscms.entity.News;
import top.ckxgzxa.newscms.service.NewsService;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 赵希奥
 * @date 2022/4/29 22:58
 * @gitHub https://github.com/CKXGZXA
 * @gitee https://gitee.com/ckxgzxa
 * @description:
 * 新闻控制器
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    /**
     * 新闻列表

     */
    @GetMapping()
    @ResponseBody
    public List<News> news() {
        List<News> newsList = newsService.listOrderByCreateTimeDesc();
        return newsList;
    }

    /**
     * 新闻详情
     */
    @ResponseBody
    @GetMapping(value = "/{id}")
    public News newsDetail(@PathVariable("id") Long id) {
        News news = newsService.getById(id);
        return news;
    }


    @PreAuthorize("hasAuthority('ADMIN')")
    @GetMapping(value = "/delete/{id}")
    public String delete(@PathVariable Long id) {
        newsService.removeById(id);
        return "success";
    }

    /**
     * 编辑新闻
     */
    @ResponseBody
    @PreAuthorize("hasAuthority('ADMIN')")
    @PutMapping(value = "/edit/{id}")
    public News put(@PathVariable("id") Long id) {
        News news = newsService.getById(id);
        return news;
    }

    /**
     * 更新新闻
     * @param news
     * @return
     */
    @PreAuthorize("hasAuthority('ADMIN')")
    @PutMapping(value = "/save/{id}")
    public String updateNews(News news) {
        // 判断是否为空, 返回错误信息
        if (news.getId() == null) {
            return "id不能为空";
        }
        if(news.getTitle() == null || "".equals(news.getTitle())){
            return "标题不能为空";
        }
        else if(news.getContent() == null || "".equals(news.getContent())){
            return "内容不能为空";
        } else {
            newsService.updateById(news);
            return "success";
        }
    }

    /**
     * 进入新闻添加页面
     * @return
     */
    @PreAuthorize("hasAuthority('ADMIN')")
    @GetMapping(value = "/add")
    public String addNews() {
        return "add";
    }

    /**
     * 添加一条新闻
     * @param news
     * @return
     */
    @PreAuthorize("hasAuthority('ADMIN')")
    @PostMapping( "/add")
    public String addNews(News news) {
        // 判断是否为空, 返回错误信息
        if(news.getTitle() == null || "".equals(news.getTitle())){
            return "标题不能为空";
        }
        else if(news.getContent() == null || "".equals(news.getContent())){
            return "内容不能为空";
        } else {
            news.setCreateTime(LocalDateTime.now());
            newsService.save(news);
            return "success";
        }
    }
}

